﻿using d1Common;
using d1Common.Interface;
using d1Project.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace d1Project.Modules.Common.doStorage.Services
{
    public class doStorageServiceLocal : doStorageServiceBase, IDoStorage
    {
        public doStorageServiceLocal()
        {
            this.storageRootPath = doServices.Instance.DoConfig.readConfigStringValue(doStorageModule.ModuleIdDefine, "Basic", "StorageRootPath", null);
            if (this.storageRootPath == null) throw new Exception("配置文件中未定义StorageRootPath");
            string _rootPath = DoEnvironment.GetExecutePath();
            if (!_rootPath.EndsWith("/")) _rootPath = _rootPath + "/";
            this.storageRootPath = this.storageRootPath.Replace("$", _rootPath);

            this.storageRootUrl = doServices.Instance.DoConfig.readConfigStringValue(doStorageModule.ModuleIdDefine, "Basic", "StorageRootUrl", null);
            if (this.storageRootUrl == null) throw new Exception("配置文件中未定义StorageRootUrl");
            if (System.Web.HttpContext.Current != null)
            {
                string _webRootPath = System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Host;
                if (System.Web.HttpContext.Current.Request.Url.Port != 80)
                {
                    _webRootPath = _webRootPath + ":" + System.Web.HttpContext.Current.Request.Url.Port.ToString();
                }

                if (!_webRootPath.EndsWith("/")) _webRootPath = _webRootPath + "/";
                this.storageRootUrl = this.storageRootUrl.Replace("$", _webRootPath);
            }
        }
        private string storageRootPath = null;
        private string storageRootUrl = null;
        private string tempRootPath = null;
        private string buildFileFullName(string _path)
        {
            return this.storageRootPath + "/" + _path;
        }
        public string getAccessUrl(string _path)
        {
            return this.storageRootUrl + "/" + _path.Replace("\\", "/");
        }
        public byte[] readFile(string _path)
        {
            string _fileFullPath = this.buildFileFullName(_path);
            return File.ReadAllBytes(_fileFullPath);
        }

        public string writeFile(string _moduleId, string _path, byte[] _content)
        {
            string _fileFullPath = this.buildFileFullName(_moduleId + "/" + _path);
            string _filePath = Path.GetDirectoryName(_fileFullPath);
            if (!Directory.Exists(_filePath)) Directory.CreateDirectory(_filePath);
            File.WriteAllBytes(_fileFullPath, _content);
            return _moduleId + "/" + _path;
        }
    }
}